/*    */ package org.appfuse.util;
/*    */ 
/*    */ import java.sql.Timestamp;
/*    */ import java.text.DateFormat;
/*    */ import java.text.SimpleDateFormat;
/*    */ import java.util.Date;
/*    */ import org.apache.commons.beanutils.ConversionException;
/*    */ import org.apache.commons.beanutils.Converter;
/*    */ import org.apache.commons.lang.StringUtils;
/*    */ 
/*    */ public class DateConverter
/*    */   implements Converter
/*    */ {
/*    */   public Object convert(Class type, Object value)
/*    */   {
/* 28 */     if (value == null)
/* 29 */       return null;
/* 30 */     if (type == Timestamp.class)
/* 31 */       return convertToDate(type, value, DateUtil.getDateTimePattern());
/* 32 */     if (type == Date.class)
/* 33 */       return convertToDate(type, value, DateUtil.getDatePattern());
/* 34 */     if (type == String.class) {
/* 35 */       return convertToString(value);
/*    */     }
/*    */ 
/* 38 */     throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
/*    */   }
/*    */ 
/*    */   protected Object convertToDate(Class<?> type, Object value, String pattern)
/*    */   {
/* 49 */     DateFormat df = new SimpleDateFormat(pattern);
/* 50 */     if ((value instanceof String)) {
/*    */       try {
/* 52 */         if (StringUtils.isEmpty(value.toString())) {
/* 53 */           return null;
/*    */         }
/*    */ 
/* 56 */         Date date = df.parse((String)value);
/* 57 */         if (type.equals(Timestamp.class)) {
/* 58 */           return new Timestamp(date.getTime());
/*    */         }
/* 60 */         return date;
/*    */       } catch (Exception e) {
/* 62 */         throw new ConversionException("Error converting String to Date", e);
/*    */       }
/*    */     }
/*    */ 
/* 66 */     throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
/*    */   }
/*    */ 
/*    */   protected Object convertToString(Object value)
/*    */   {
/* 75 */     if ((value instanceof Date)) {
/* 76 */       DateFormat df = new SimpleDateFormat(DateUtil.getDatePattern());
/* 77 */       if ((value instanceof Timestamp)) {
/* 78 */         df = new SimpleDateFormat(DateUtil.getDateTimePattern());
/*    */       }
/*    */       try
/*    */       {
/* 82 */         return df.format(value);
/*    */       } catch (Exception e) {
/* 84 */         throw new ConversionException("Error converting Date to String", e);
/*    */       }
/*    */     }
/* 87 */     return value.toString();
/*    */   }
/*    */ }

